package org.groovyflow.aop

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.groovyflow.json.*

class StartupAop{
	static void exe(){
		//If enableGlobally causes too much strain on memory.
		//we could either 1) have the GroovyFlowFilter pass
		//a GroovyFlowResponse/Request down the chain.
		//Those objects would simply be JDK dynamic proxies,
		//and would allow us to attach the methods below to 
		//classes rather than interfaces, or 2)
		//have the GroovyFlowFilter call the current method
		//once, passing in the application's request and 
		//response.
		ExpandoMetaClass.enableGlobally() 
		
		HttpServletResponse.metaClass.writeJson = {obj ->
			if(obj == null) throw new IllegalArgumentException("Null not allowed")
			if(obj instanceof Map)
				delegate.getWriter().write(JsonUtil.mapToJson(obj))
			else if(obj instanceof String)
				delegate.getWriter().write(obj)
			else if(obj instanceof List)
				delegate.getWriter().write(JsonUtil.toJson(obj))
			else 
				throw new IllegalArgumentException(obj.getClass().getName() + " not supported.")
		}
		//This used to be before getJsonForm, but for some reason it failed,
		//and I saw playing with the GroovyConsole that order can matter in these
		//things even when it shouldn't.
		HttpServletRequest.metaClass.putJson = {obj ->
			if(obj == null) throw new IllegalArgumentException("Null not allowed")
        	if(obj instanceof Map)
				delegate.setAttribute("jsonAttr", JsonUtil.mapToJson(obj))
			else if(obj instanceof String)
				delegate.setAttribute("jsonAttr", obj)
			else 
				throw new IllegalArgumentException(obj.getClass().getName() + " not supported.")
		}		
		
		HttpServletRequest.metaClass.getJsonForm = { ->
		    String incommingJson = delegate.getParameter("jsonAttr")
        	return JsonUtil.toObject(incommingJson)
		}
		
	}

}